# -*- coding: utf-8 -*-

import ldap
from django.conf import settings
from ldap.controls import SimplePagedResultsControl


class LdapSyncUtils(object):
    """LDAP配置类"""

    # 所需的初始配置参数
    def __init__(self):
        self.ldap_username = settings.LDAP_USER_NAME
        self.ldap_password = settings.LDAP_PASSWORD
        self.ldapInit = ldap.initialize(settings.LDAP_HOST)

    @property
    def ldap_column_mapping(self):
        return self._ldap_column_mapping

    @ldap_column_mapping.setter
    def ldap_column_mapping(self, ldapColumnMapping):
        self._ldap_column_mapping = ldapColumnMapping

    def bind_Connect(self):
        return self.ldapInit.simple_bind_s(self.ldap_username, self.ldap_password), self.ldapInit

    def close_ldapConn(self, conn):
        conn.unbind_s()

    def value_health_check(self, value):
        try:
            valueTrue = str(value, encoding='utf-8')

        except (UnicodeDecodeError,):
            valueTrue = "Null"
        return valueTrue

    def get_UserData(self, location, dicColumnMapping: dict):
        pg_contol = SimplePagedResultsControl(True, size=500, cookie="")
        ldapColumns = [x for x in dicColumnMapping]
        mysqLColumns = [y for y in dicColumnMapping.values()]
        ldap_list = []
        while True:
            self.msgid = self.ldapInit.search_ext(location, ldap.SCOPE_ONELEVEL,
                                                  '(objectClass=user)', ldapColumns,
                                                  serverctrls=[pg_contol])
            _a, res_data, _b, srv_ctrls = self.ldapInit.result3(self.msgid)
            for userRecord in res_data:
                dic = {}
                for num in range(0, len(ldapColumns)):
                    # 检查数据是否可以Unicode
                    try:
                        dic[mysqLColumns[num]] = self.value_health_check(userRecord[1][ldapColumns[num]][0])
                    except:
                        dic[mysqLColumns[num]] = ""
                    # print(userRecord)
                ldap_list.append(dic)

            cookie = srv_ctrls[0].cookie
            if cookie:
                pg_contol.cookie = cookie
            else:
                break
        return ldap_list
